
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>JSJaC Simple Client</title>

    <script type="text/javascript" src="../jsjac.js"></script>
    <!-- comment in above and uncomment below if you want to modify/hack
         on jsjac -->
    <!--script type="text/javascript" src="../src/JSJaC.js"></script-->

    <!-- if you want to enable debugging uncomment line below
         debugger available at 
          http://svn.stefan-strigler.de/JSDebugger/trunk -->
    <!--script type="text/javascript" src="Debugger.js"></script-->

    <script language="JavaScript" type="text/javascript">
// <![CDATA[
function handleIQ(aIQ) {
  document.getElementById('iResp').innerHTML += 
    "<div class='msg'>IN (raw): " +aIQ.xml().htmlEnc() + '</div>';
  document.getElementById('iResp').lastChild.scrollIntoView();
  con.send(aIQ.errorReply(ERR_FEATURE_NOT_IMPLEMENTED));
}

function handleMessage(aJSJaCPacket) {
  var html = '';
  html += '<div class="msg"><b>Received Message from '+aJSJaCPacket.getFromJID()+':</b><br/>';
  html += aJSJaCPacket.getBody().htmlEnc() + '</div>';
  document.getElementById('iResp').innerHTML += html;
  document.getElementById('iResp').lastChild.scrollIntoView();
}

function handlePresence(aJSJaCPacket) {
  var html = '<div class="msg">';
  if (!aJSJaCPacket.getType() && !aJSJaCPacket.getShow()) 
    html += '<b>'+aJSJaCPacket.getFromJID()+' has become available.</b>';
  else {
    html += '<b>'+aJSJaCPacket.getFromJID()+' has set his presence to ';
    if (aJSJaCPacket.getType())
      html += aJSJaCPacket.getType() + '.</b>';
    else
      html += aJSJaCPacket.getShow() + '.</b>';
    if (aJSJaCPacket.getStatus())
      html += ' ('+aJSJaCPacket.getStatus().htmlEnc()+')';
  }
  html += '</div>';

  document.getElementById('iResp').innerHTML += html;
  document.getElementById('iResp').lastChild.scrollIntoView();
}

function handleError(e) {
  document.getElementById('err').innerHTML = "An error occured:<br />"+ 
    ("Code: "+e.getAttribute('code')+"\nType: "+e.getAttribute('type')+
    "\nCondition: "+e.firstChild.nodeName).htmlEnc(); 
  document.getElementById('login_pane').style.display = '';
  document.getElementById('sendmsg_pane').style.display = 'none';
  
  if (con.connected())
    con.disconnect();
}

function handleStatusChanged(status) {
  oDbg.log("status changed: "+status);
}

function handleConnected() {
  document.getElementById('login_pane').style.display = 'none';
  document.getElementById('sendmsg_pane').style.display = '';
  document.getElementById('err').innerHTML = '';

  con.send(new JSJaCPresence());
}

function handleDisconnected() {
  document.getElementById('login_pane').style.display = '';
  document.getElementById('sendmsg_pane').style.display = 'none';
}

function handleIqVersion(iq) {
  con.send(iq.reply([
                     iq.buildNode('name', 'jsjac simpleclient'),
                     iq.buildNode('version', JSJaC.Version),
                     iq.buildNode('os', navigator.userAgent)
                     ]));
  return true;
}

function handleIqTime(iq) {
  var now = new Date();
  con.send(iq.reply([iq.buildNode('display',
                                  now.toLocaleString()),
                     iq.buildNode('utc',
                                  now.jabberDate()),
                     iq.buildNode('tz',
                                  now.toLocaleString().substring(now.toLocaleString().lastIndexOf(' ')+1))
                     ]));
  return true;
}

function doLogin(aForm) {
  document.getElementById('err').innerHTML = ''; // reset

  try {
    // setup args for contructor
    oArgs = new Object();
    oArgs.httpbase = aForm.http_base.value;
    oArgs.timerval = 2000;

    if (typeof(oDbg) != 'undefined')
      oArgs.oDbg = oDbg;

    if (aForm.backend[0].checked)
      con = new JSJaCHttpBindingConnection(oArgs);
    else
      con = new JSJaCHttpPollingConnection(oArgs);

    setupCon(con);

    // setup args for connect method
    oArgs = new Object();
    oArgs.domain = aForm.server.value;
    oArgs.username = aForm.username.value;
    oArgs.resource = 'jsjac_simpleclient';
    oArgs.pass = aForm.password.value;
    oArgs.register = aForm.register.checked;
    con.connect(oArgs);
  } catch (e) {
    document.getElementById('err').innerHTML = e.toString();
  } finally {
    return false;
  }
}

function setupCon(con) {
    con.registerHandler('message',handleMessage);
    con.registerHandler('presence',handlePresence);
    con.registerHandler('iq',handleIQ);
    con.registerHandler('onconnect',handleConnected);
    con.registerHandler('onerror',handleError);
    con.registerHandler('status_changed',handleStatusChanged);
    con.registerHandler('ondisconnect',handleDisconnected);

    con.registerIQGet('query', NS_VERSION, handleIqVersion);
    con.registerIQGet('query', NS_TIME, handleIqTime);
}

function sendMsg(aForm) {
  if (aForm.msg.value == '' || aForm.sendTo.value == '')
    return false;

  if (aForm.sendTo.value.indexOf('@') == -1)
    aForm.sendTo.value += '@' + con.domain;

  try {
    var aMsg = new JSJaCMessage();
    aMsg.setTo(new JSJaCJID(aForm.sendTo.value));
    aMsg.setBody(aForm.msg.value);
    con.send(aMsg);

    aForm.msg.value = '';

    return false;
  } catch (e) {
    html = "<div class='msg error''>Error: "+e.message+"</div>"; 
    document.getElementById('iResp').innerHTML += html;
    document.getElementById('iResp').lastChild.scrollIntoView();
    return false;
  }
}

function quit() {
  var p = new JSJaCPresence();
  p.setType("unavailable");
  con.send(p);
  con.disconnect();

  document.getElementById('login_pane').style.display = '';
  document.getElementById('sendmsg_pane').style.display = 'none';
}

function init() {
  if (typeof(Debugger) == 'function') {
    oDbg = new Debugger(2,'simpleclient');
    oDbg.start();
  } else {
    // if you're using firebug or safari, use this for debugging
    //oDbg = new JSJaCConsoleLogger(2);
    // comment in above and remove comments below if you don't need debugging
    oDbg = function() {};
    oDbg.log = function() {};
  }


  try { // try to resume a session
    if (JSJaCCookie.read('btype').getValue() == 'binding')
      con = new JSJaCHttpBindingConnection({'oDbg':oDbg});
    else
      con = new JSJaCHttpPollingConnection({'oDbg':oDbg});

    setupCon(con);

    if (con.resume()) {

      document.getElementById('login_pane').style.display = 'none';
      document.getElementById('sendmsg_pane').style.display = '';
      document.getElementById('err').innerHTML = '';

    }
  } catch (e) {} // reading cookie failed - never mind

}
onload = init;

onerror = function(e) { 
  document.getElementById('err').innerHTML = e; 

  document.getElementById('login_pane').style.display = '';
  document.getElementById('sendmsg_pane').style.display = 'none';

  if (con && con.connected())
    con.disconnect();
  return false; 
};

onunload = function() {
  if (typeof con != 'undefined' && con && con.connected()) {
  // save backend type
    if (con._hold) // must be binding
      (new JSJaCCookie('btype','binding')).write();
    else
      (new JSJaCCookie('btype','polling')).write();
    if (con.suspend) {
      con.suspend(); 
    }
  }
};

// ]]>
    </script>
    <style type="text/css">
/*<![CDATA[*/
body {
font-family: "Bitstream Vera Sans", "Verdana", sans;
font-size: 0.8em;
margin: 12px;
}
h2 {
border-bottom: 1px solid grey;
}
input {
border: 1px solid grey;
}
#iResp {
width: 420px;
height: 260px;
overflow: auto;
border: 2px dashed grey;
padding: 4px;
}
#msgArea {
width: 420px;
height: 45px;
padding: 4px;
margin: 0;
border: 2px dashed grey;
}
.spaced {
margin-bottom: 4px;
}
.msg {
border-bottom: 1px solid black;
}
.error {
font-weight: bold;
color: red;
}
/*]]>*/
    </style>
  </head>
  <body>
  <h1><a href="#" onclick="location.reload();">JSJaC Simple Client</a></h1>

  <div id="err"></div>

  <div id="login_pane">
    <h2>Login</h2>
    <form name="loginForm" onSubmit="return doLogin(this);" action="#">
      <table>
	<tr><th>Backend Type</th><td><input type="radio" name="backend" value="binding" id="backend1" tabindex="1"/> <label for="backend1">HTTP Binding</label><br /> <input type="radio" name="backend" value="polling" id="backend2" tabindex="2"/> <label for="backend2">HTTP Polling</label></td></tr>
	<tr><th><label for="http_base">HTTP Base</label></th><td><input type="text" name="http_base" id="http_base" tabindex="3"/></td></tr>
        <tr><th colspan="2"><hr noshade size="1"/></th></tr>
	<tr><th><label for="server">Jabber Server</label></th><td><input type="text" name="server" id="server" tabindex="4"/></td></tr>
	<tr><th><label for="username">Username</label></th><td><input type="text" name="username" id="username" tabindex="5"/></td></tr>
	<tr><th><label for="password">Password</label></th><td><input type="password" name="password" id="password" tabindex="6" /></td></tr>
	<tr><th></th><td><input type="checkbox" name="register" id="register_checkbox" /> <label for="register_checkbox">Register new account</label></td></tr>
	<tr><td>&nbsp;</td><td><input type="submit" value="Login" tabindex="7"></td></tr>
     </table>
    </form>
  </div>

  <div id="sendmsg_pane" style="display:none;">
    <h2>Incoming:</h2>
    <div id="iResp"></div>
    <h2>Send Message</h2>
      <form name="sendForm" onSubmit="return sendMsg(this);" action="#">
	<div class="spaced"><b>To:</b> <input type="text" name="sendTo" tabindex="1"></div>
	<div class="spaced"><textarea name="msg" id='msgArea' rows="3" cols="80" tabindex="2"></textarea></div>
	<div class="spaced"><input type="submit" value="Send" tabindex="3"> * <input type="button" value="Quit" tabindex="4" onclick="return quit();"></div>
      </form>
    </div>
  </body>
</html>
